package com.bingo.food.orderservicemanager.service;

import com.bingo.food.orderservicemanager.dao.OrderDetailDao;
import com.bingo.food.orderservicemanager.dto.OrderMessageDTO;
import com.bingo.food.orderservicemanager.moodymq.listener.AbstractMessageListener;
import com.bingo.food.orderservicemanager.moodymq.sender.TransMessageSender;
import com.bingo.food.orderservicemanager.po.OrderDetailPO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.bingo.food.orderservicemanager.enummeration.OrderStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service
public class OrderMessageService extends AbstractMessageListener {

    @Autowired
    TransMessageSender transMessageSender;

    @Autowired
    private OrderDetailDao orderDetailDao;

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void receviceMessage(Message message) throws IOException {
        log.info("restaurant:message:{}", new String(message.getBody()));
        try {
            OrderMessageDTO orderMessageDTO = objectMapper.readValue(message.getBody(),
                    OrderMessageDTO.class);
            OrderDetailPO orderPO = orderDetailDao.selectOrder(orderMessageDTO.getOrderId());
            switch (orderPO.getStatus()) {
                case 0:
                    if (orderMessageDTO.getConfirmed() && null != orderMessageDTO.getPrice()) {

                        orderPO.setStatus(OrderStatus.RESTAURANT_CONFIRMED.ordinal());
                        orderPO.setPrice(orderMessageDTO.getPrice());
                        orderDetailDao.update(orderPO);
                        transMessageSender.send("exchange.order.deliveryman", "key.deliveryman", orderPO);
                    } else {
                        orderPO.setStatus(OrderStatus.FAILED.ordinal());
                        orderDetailDao.update(orderPO);
                    }
                    break;
                case 1:
                    if (null != orderMessageDTO.getDeliverymanId()) {
                        orderPO.setStatus(OrderStatus.DELIVERYMAN_CONFIRMED.ordinal());
                        orderPO.setDeliverymanId(orderMessageDTO.getDeliverymanId());
                        orderDetailDao.update(orderPO);
                        transMessageSender.send("exchange.order.settlement", "key.settlement", orderPO);
                    } else {
                        orderPO.setStatus(OrderStatus.FAILED.ordinal());
                        orderDetailDao.update(orderPO);
                    }
                    break;
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

}
